/*
** actions.c for  in /home/costa_k//rendulocal/cunix/philosophe/epi-philosophes
** 
** Made by kevin costa
** Login   <costa_k@epitech.net>
** 
** Started on  Wed May  4 16:55:50 2011 kevin costa
** Last update Wed May  4 17:49:59 2011 kevin costa
*/

# define  _XOPEN_SOURCE  (500)

#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include "actions.h"

t_philo			*check_next(t_philo *philo)
{
  if (philo->p == 6)
    philo = philo->head;
  else
    philo = philo->next;
  return (philo);
}

void			donne(t_philo *philo, int dispo)
{
  t_philo		*tmp;

  tmp = philo;
  philo = check_next(philo);
  while (dispo != 0)
    {
      if (philo->g == vide && dispo != 0)
	{
	  if (printf("Philo:(%i) donne baguette a (%i)\n", tmp->p, philo->p) == 0)
	    exit(EXIT_FAILURE);
	  philo->g = plein;
	  tmp->g = vide;
	  dispo--;
	}
      else if (philo->d == vide && dispo != 0)
	{
	  if (printf("Philo: (%i) donne baguette a (%i)\n", tmp->p, philo->p) == 0)
	    exit(EXIT_FAILURE);
	  philo->d = plein;
	  tmp->d = vide;
	  dispo--;
	}
      philo = check_next(philo);
    }
}

void			*mange(void *voidphilo)
{
  t_philo		*philo;

  philo = (t_philo*)voidphilo;
  printf("Philosophe %i commence a manger, Energie : %i %%\n",
	 philo->p, philo->j);
  errno = 0;
  errno = usleep((useconds_t)10);
  if (errno != 0)
    {
      xwrite(2, strerror(errno), strlen(strerror(errno)));
      exit(EXIT_FAILURE);
    }
  pthread_mutex_lock(&lock);
  pthread_mutex_unlock(&lock);
  printf("Philosophe %i a fini de manger, Energie : %i %%\n",
	 philo->p, philo->j);
  pthread_exit(NULL);
}

void			*pense(void *voidphilo)
{
  t_philo		*philo;

  philo = (t_philo*)voidphilo;
  printf("Philosophe %i commence a penser, Energie : %i %%\n",
	 philo->p, philo->j);
  errno = 0;
  errno = usleep((useconds_t)20);
  if (errno != 0)
    {
      xwrite(2, strerror(errno), strlen(strerror(errno)));
      exit(EXIT_FAILURE);
    }
  pthread_mutex_lock(&lock);
  philo->j -= 10;
  if (philo->j < 0)
    philo->j = 0;
  pthread_mutex_unlock(&lock);
  printf("Philosophe %i a fini de penser, Energie : %i %%\n",
	 philo->p, philo->j);
  pthread_exit(NULL);
}

void			*repos(void *voidphilo)
{
  t_philo		*philo;

  philo = (t_philo*)voidphilo;
  printf("Philosophe %i se repose, Energie : %i %%\n",
	 philo->p, philo->j);
  errno = 0;
  errno = usleep((useconds_t)10);
  if (errno != 0)
    {
      xwrite(2, strerror(errno), strlen(strerror(errno)));
      exit(EXIT_FAILURE);
    }
  pthread_mutex_lock(&lock);
  philo->j += 20;
  if (philo->j > 100)
    philo->j = 100;
  pthread_mutex_unlock(&lock);
  printf("Philosophe %i a fini de se reposer, Energie : %i %%\n",
	 philo->p, philo->j);
  pthread_exit(NULL);
}
